/*
 *    Copyright 2014 Sam Y Ge
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.strx;

/**
 * 通过字符串读取Tag的TagReader
 * 
 * 读取以字符串形式的XML文档
 * 
 * @see TagReader
 * @see StreamTagReader
 * 
 * @author <a href="mailto:samuel.y@foxmail.com">Sam Y Ge</a>
 */
class StringTagReader extends TagReader {
	/* xml字符串 */
	private String xml;

	/* 结束位置 */
	private int end;

	/**
	 * 通过给定的字符串来构造
	 * 
	 * @param xml
	 *            XML字符串
	 */
	StringTagReader(String xml) {
		super();
		this.xml = xml;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	Tag getNextTag() {
		currTagStr = null;
		currTag = null;

		int start = xml.indexOf(Tag.TAG_START, end);
		if (-1 != start) {
			// 判定是否最后一个标签
			end = xml.indexOf(Tag.TAG_START, start + 1);

			if (-1 == end) {
				end = xml.length();
				currTagStr = xml.substring(start).trim();
			} else {
				currTagStr = xml.substring(start, end).trim();
			}

			TagType type = getTagType();

			/*
			 * 针对CDATA节点需要做特殊处理
			 */
			if (type == TagType.CDATA) {
				end = xml.indexOf(Tag.CDATA_TAG_END);
				if (-1 != end) {
					currTagStr = xml.substring(start, end + 3).trim();
				}
			}

			buildTag();
		}

		return currTag;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	void clean() {
		xml = null;
	}

}
